namespace Bowlus.FrontEnd.RequestRouting.ApplicationDeployment
{
    using System;

    using Bowlus.Common;
    using Bowlus.Common.Communications;

    public class MoveApplicationRequest : ApplicationDeploymentRequest
    {
        public MoveApplicationRequest(TenantDeployment tenantDeployment, ApplicationHost fromApplicationHost, ApplicationHost toApplicationHost)
            : base(tenantDeployment)
        {
            this.FromHost = fromApplicationHost;
            this.ToHost = toApplicationHost;
        }

        public ApplicationHost FromHost { get; private set; }

        public ApplicationHost ToHost { get; private set; }

        public override Guid SendDeploymentRequest()
        {
            var deploymentServiceClient = new CommunicationsClient();

            // When we receive this method for the move app request, we will need to deploy 
            var message = this.ConstructMessage(BowlusMessageType.DeployApp);

            deploymentServiceClient.SendMessageToRoleInstance(message, this.ToHost.DeploymentManagerEndpoint, Settings.AppHostRoleName);

            return message.MessageId;
        }

        public override bool CanUpdateConfiguration(BowlusMessage response, out Guid nextMessageId)
        {
            if (response.MessageType == BowlusMessageType.AppDeployed)
            {
                // Need to send a delete request now
                var message = this.ConstructMessage(BowlusMessageType.DeleteApp);

                var deploymentServiceClient = new CommunicationsClient();

                deploymentServiceClient.SendMessageToRoleInstance(message, this.ToHost.DeploymentManagerEndpoint, Settings.AppHostRoleName);

                nextMessageId = message.MessageId;
                return false;
            }

            if (response.MessageType == BowlusMessageType.AppDeleted)
            {
                nextMessageId = Guid.Empty;
                return true;
            }

            nextMessageId = Guid.Empty;
            return false;
        }
    }
}